<?php

class PublicAction extends Action
{
    protected $Config;
    protected $SysConfig;
    protected $Categorys;
    protected $Mod = array();
    protected $Model;
    protected $Lang;

    public function _initialize()
    {
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: token,Origin, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Methods: POST,GET');

        $this->SysConfig = getSysConfig();
        C($this->SysConfig);

        $this->Model = getCache('Model');

        foreach ($this->Model as $key => $val) {
            $this->Mod[$val['tablename']] = $val['id'];
        }

        $this->Lang = getCache('Lang');
        $default_lang = C('DEFAULT_LANG');

        $l = I('get.l', '');
        $lang = isset($this->Lang[$l]) ? $l : $default_lang;

        define('LANG_NAME', $lang);
        define('LANG_ID', $this->Lang[$lang]['id']);

        //获取栏目
        $this->Categorys = getCache('Category_' . $lang);

        //获取网站配置信息
        $this->Config = getCache('Config_' . $lang);
    }

    public function upload()
    {
        $typeArr = array("jpg", "png", "rar", "jpeg"); //允许上传文件格式
        $path = "./uploads/temp/"; //上传路径
        if (!is_dir($path)) {
            // 尝试创建目录
            if (!mkdir($path)) {
                echo json_encode(array("error" => '上传目录' . $path . '不存在'));
                return false;
            }
        }

        if (isset($_POST)) {
            $name = $_FILES['file']['name'];
            $size = $_FILES['file']['size'];
            $name_tmp = $_FILES['file']['tmp_name'];
            if (empty($name)) {
                echo json_encode(array("error" => "您还未选择文件"));
                exit;
            }
            $type = strtolower(substr(strrchr($name, '.'), 1)); //获取文件类型

            if (!in_array($type, $typeArr)) {
                echo json_encode(array("error" => "请上传jpg,rar或zip类型的文件！"));
                exit;
            }
            if ($size > 1024 * 1024*5) { //上传大小
                echo json_encode(array("error" => "图片大小已超过1MB！"));
                exit;
            }

            $pic_name = time() . rand(10000, 99999) . "." . $type; //图片名称
            $pic_url = "/uploads/temp/" . $pic_name; //上传后图片路径+名称
            if (move_uploaded_file($name_tmp, $pic_url)) { //临时文件转移到目标文件夹
                echo json_encode(array("error" => "0", "data" => $pic_url, "name" => $pic_name));
            } else {
                echo json_encode(array("error" => "上传有误，清检查服务器配置！"));
            }
        }
    }
}